<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, computed } from 'vue'
import { generateUUID } from '@/utils/uuid'
import { marked } from 'marked'
import { useUserStore } from '@/stores/user'
import Sidebar from '@/components/sidebar/Sidebar.vue'
import type { ChatItem } from '@/types/chat'

const message = ref('')
const isLoading = ref(false)
const chatContainerRef = ref<HTMLElement | null>(null)
const messageInputRef = ref<HTMLTextAreaElement | null>(null)
const modelDropdownRef = ref<HTMLElement | null>(null)
const currentModel = ref('GPT-4')
const showModelSelector = ref(false)

// 聊天模式：text 或 image
const chatMode = ref<'text' | 'image'>('text')
const isGeneratingImage = ref(false)

// 侧边栏状态
const showSidebar = ref(true)
const currentChatId = ref<string | null>(null)
const sidebarCollapsed = ref(false)

const userStore = useUserStore()

// 可用的AI模型列表 - 基于后端实际支持的平台和模型
const availableModels = [
  // OpenAI 文本模型
  { id: 'gpt-4o', name: 'GPT-4o', platform: 'openai', description: '最新版本，更快更智能', provider: 'OpenAI', type: 'text' },
  { id: 'gpt-4', name: 'GPT-4', platform: 'openai', description: '强大的推理能力', provider: 'OpenAI', type: 'text' },
  { id: 'gpt-3.5-turbo', name: 'GPT-3.5 Turbo', platform: 'openai', description: '快速响应，成本较低', provider: 'OpenAI', type: 'text' },
  { id: 'gpt-4-turbo', name: 'GPT-4 Turbo', platform: 'openai', description: '更快的GPT-4版本', provider: 'OpenAI', type: 'text' },
  
  // OpenAI 图片生成模型
  { id: 'dall-e-3', name: 'DALL-E 3', platform: 'openai', description: '最新图片生成模型，质量更高', provider: 'OpenAI', type: 'image' },
  { id: 'dall-e-2', name: 'DALL-E 2', platform: 'openai', description: '经典图片生成模型', provider: 'OpenAI', type: 'image' },
  
  // 阿里云模型
  { id: 'qwen-plus', name: 'Qwen Plus', platform: 'ali', description: '通义千问增强版', provider: '阿里云', type: 'text' },
  { id: 'qwen-turbo', name: 'Qwen Turbo', platform: 'ali', description: '通义千问快速版', provider: '阿里云', type: 'text' },
  { id: 'qwen-max', name: 'Qwen Max', platform: 'ali', description: '通义千问旗舰版', provider: '阿里云', type: 'text' }
]

// 当前选中的模型
const selectedModel = ref(availableModels[0])

// 计算属性：是否已登录
const isLoggedIn = computed(() => userStore.isAuthenticated)

// 计算属性：根据当前模式筛选可用的模型
const filteredModels = computed(() => {
  if (chatMode.value === 'text') {
    return availableModels.filter(model => !model.type || model.type === 'text')
  } else {
    return availableModels.filter(model => model.type === 'image')
  }
})

// 计算属性：当前模式下推荐的默认模型
const defaultModelForMode = computed(() => {
  if (chatMode.value === 'text') {
    return availableModels.find(model => model.id === 'gpt-4o') || availableModels[0]
  } else {
    return availableModels.find(model => model.id === 'dall-e-3') || availableModels.find(model => model.type === 'image')
  }
})

// 切换模型选择器显示状态
const toggleModelSelector = () => {
  showModelSelector.value = !showModelSelector.value
}

// 选择模型
const selectModel = (model: typeof availableModels[0]) => {
  selectedModel.value = model
  currentModel.value = model.name
  showModelSelector.value = false
  console.log('🔄 切换到模型:', {
    name: model.name,
    id: model.id,
    platform: model.platform,
    provider: model.provider
  })
}

// 点击外部关闭模型选择器
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest('.model-selector-container')) {
    showModelSelector.value = false
  }
}

// 切换聊天模式
const toggleChatMode = () => {
  chatMode.value = chatMode.value === 'text' ? 'image' : 'text'
  
  // 自动切换到对应模式的默认模型
  const newDefaultModel = defaultModelForMode.value
  if (newDefaultModel) {
    selectedModel.value = newDefaultModel
    currentModel.value = newDefaultModel.name
  }
  
  console.log('🔄 切换聊天模式:', {
    mode: chatMode.value === 'text' ? '文本聊天' : '图片生成',
    model: selectedModel.value.name,
    modelId: selectedModel.value.id
  })
}

// 打开图片
const openImage = (imageUrl: string) => {
  window.open(imageUrl, '_blank')
}

// 图片加载错误处理
const handleImageError = (event: Event, messageId: string) => {
  console.error('❌ 图片加载失败:', event)
  const imageMessage = chatMessages.value.find(item => item.id === messageId)
  if (imageMessage) {
    imageMessage.message = '❌ 图片加载失败，可能链接已过期'
  }
}

// 验证当前模型是否适合当前聊天模式
const validateModelForMode = () => {
  const currentModelType = selectedModel.value.type || 'text'
  const expectedType = chatMode.value
  
  if (currentModelType !== expectedType) {
    console.warn('⚠️ 模型类型不匹配，自动切换模型')
    const newDefaultModel = defaultModelForMode.value
    if (newDefaultModel) {
      selectedModel.value = newDefaultModel
      currentModel.value = newDefaultModel.name
      console.log('✅ 已自动切换到:', newDefaultModel.name)
    }
  }
}

// 侧边栏相关方法
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
  // 保存侧边栏状态到localStorage
  localStorage.setItem('sidebarVisible', showSidebar.value.toString())
}

const handleChatSelected = (chat: ChatItem | null) => {
  if (chat) {
    currentChatId.value = chat.id
    // 这里可以加载对应聊天的消息历史
    loadChatMessages(chat.id)
    console.log('🔄 选择聊天:', chat.title)
  } else {
    // 新建对话
    currentChatId.value = null
    chatMessages.value = []
    console.log('📝 新建对话')
  }
}

// 监听侧边栏折叠状态变化
const handleSidebarCollapseChange = (collapsed: boolean) => {
  sidebarCollapsed.value = collapsed
}

const handleViewAllHistory = () => {
  console.log('📚 查看所有历史')
  // 这里可以打开历史记录页面或模态框
}

const handleUpgradeToPro = () => {
  console.log('⭐ 升级到Pro')
  // 这里可以打开升级页面
}

const handleOpenSettings = () => {
  console.log('⚙️ 打开设置')
  // 这里可以打开设置页面或模态框
}

// 加载聊天消息（预留接口）
const loadChatMessages = async (chatId: string) => {
  try {
    // 这里调用API加载聊天历史
    console.log('🔄 加载聊天消息:', chatId)
    // const messages = await chatService.getChatMessages(chatId)
    // chatMessages.value = messages
  } catch (error) {
    console.error('加载聊天消息失败:', error)
  }
}

type ChatMessage = {
  role: 'user' | 'assistant'
  id: string
  message: string
  type?: 'text' | 'image'
  imageUrl?: string
  imagePrompt?: string
}
const chatMessages = ref<ChatMessage[]>([])

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 设置建议消息
const setSuggestedMessage = (text: string) => {
  message.value = text

  // 聚焦输入框
  nextTick(() => {
    if (messageInputRef.value) {
      messageInputRef.value.focus()
      adjustTextareaHeight()
    }
  })
}

// 处理Shift+Enter键盘事件
const handleShiftEnter = (event: KeyboardEvent) => {
  // Shift+Enter 允许换行，不做任何处理
}

// 自动调整文本框高度
const adjustTextareaHeight = () => {
  if (messageInputRef.value) {
    messageInputRef.value.style.height = 'auto'
    messageInputRef.value.style.height = `${Math.min(messageInputRef.value.scrollHeight, 128)}px`
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainerRef.value) {
    chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight
  }
}

// 格式化消息内容（处理Markdown）
const formatMessageContent = (content: string) => {
  try {
    // 使用marked库将markdown转换为HTML
    return marked(content, {
      breaks: true,
      gfm: true
    })
  } catch (error) {
    console.error('Error formatting message:', error)
    return content
  }
}

// 复制消息
const copyMessage = (text: string) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      // 可以添加一个复制成功的提示
      console.log('文本已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
    })
}

// 重新生成消息
const regenerateMessage = (index: number) => {
  // 找到用户最后一条消息
  const lastUserMessageIndex = chatMessages.value
    .slice(0, index + 1)
    .map((msg, i) => ({ msg, i }))
    .filter(item => item.msg.role === 'user')
    .pop()

  if (lastUserMessageIndex) {
    const userMessage = chatMessages.value[lastUserMessageIndex.i].message

    // 删除从用户消息之后的所有消息
    chatMessages.value = chatMessages.value.slice(0, lastUserMessageIndex.i + 1)

    // 添加空的助手消息
    let resId = generateUUID()
    chatMessages.value.push({
      id: resId,
      message: '',
      role: 'assistant',
    })

    // 发送请求
    sendStreamRequest(userMessage, resId)
  }
}

// 发送消息
const sendMessageClick = () => {
  if (message.value.trim() === '' || isLoading.value || isGeneratingImage.value) {
    return
  }

  // 验证模型是否适合当前模式
  validateModelForMode()

  const userMessage = message.value
  
  if (chatMode.value === 'text') {
    // 文本聊天模式
    isLoading.value = true

    // 添加用户消息
    chatMessages.value.push({
      id: generateUUID(),
      message: userMessage,
      role: 'user',
      type: 'text'
    })

    // 添加空的助手消息
    let resId = generateUUID()
    chatMessages.value.push({
      id: resId,
      message: '',
      role: 'assistant',
      type: 'text'
    })

    // 滚动到底部
    scrollToBottom()

    // 清空输入框
    message.value = ''
    if (messageInputRef.value) {
      messageInputRef.value.style.height = 'auto'
    }

    // 发送请求
    sendStreamRequest(userMessage, resId)
  } else {
    // 图片生成模式
    generateImage(userMessage)
  }
}

// 发送流式请求
const sendStreamRequest = (userMessage: string, resId: string) => {
  // 准备请求参数
  const requestBody = {
    platform: selectedModel.value.platform,
    model: selectedModel.value.id,
    message: userMessage
  }
  
  console.log('🚀 发送聊天请求:', {
    url: '/api/ai/chat/text/stream',
    model: selectedModel.value.name,
    platform: selectedModel.value.platform,
    modelId: selectedModel.value.id,
    token: userStore.token ? '已设置' : '未设置',
    message: userMessage.substring(0, 50) + '...'
  })

  // 使用 fetch API 发送 POST 请求处理流式响应
  fetch('/api/ai/chat/text/stream', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
    },
    body: JSON.stringify(requestBody)
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const reader = response.body?.getReader()
      const decoder = new TextDecoder()
      let buffer = ''

      function readStream(): Promise<void> {
        return reader!.read().then(({ done, value }) => {
          if (done) {
            isLoading.value = false
            scrollToBottom()
            return
          }

          // 将新数据添加到缓冲区
          buffer += decoder.decode(value, { stream: true })

          // 按空行分割事件（SSE 事件以双换行符分隔）
          const events = buffer.split('\n\n')

          // 保留最后一个可能不完整的事件
          buffer = events.pop() || ''

          // 处理完整的事件
          for (const eventData of events) {
            if (!eventData.trim()) continue

            const lines = eventData.split('\n')
            let currentEvent = ''
            let currentData = ''

            for (const line of lines) {
              if (line.startsWith('event:')) {
                currentEvent = line.slice(6).trim()
              } else if (line.startsWith('data:')) {
                currentData = line.slice(5).trim()
              }
            }

            // 处理完整的事件
            if (currentEvent === 'delta' && currentData) {
              try {
                const parsed = JSON.parse(currentData)
                const dstMessage = chatMessages.value.find((item) => item.id === resId)
                if (dstMessage && parsed.delta) {
                  dstMessage.message += parsed.delta
                  scrollToBottom()
                }
              } catch (e) {
                console.warn('Failed to parse SSE data:', currentData)
              }
            } else if (currentEvent === 'done' || currentData === '[DONE]') {
              isLoading.value = false
              scrollToBottom()
              return
            }
          }

          return readStream()
        })
      }

      return readStream()
    })
    .catch(err => {
      console.error('❌ 聊天请求失败:', {
        error: err.message,
        model: selectedModel.value.name,
        platform: selectedModel.value.platform,
        modelId: selectedModel.value.id
      })
      isLoading.value = false

      // 在出错时更新助手消息
      const errorMessage = chatMessages.value.find(item => item.id === resId)
      if (errorMessage) {
        if (err.message.includes('403')) {
          errorMessage.message = '❌ 访问被拒绝，可能是因为您尚未登录或登录已过期。请先登录后再尝试。'
        } else if (err.message.includes('401')) {
          errorMessage.message = '❌ 未授权访问，请重新登录后再试。'
        } else if (err.message.includes('404')) {
          errorMessage.message = '❌ 找不到请求的资源，请检查API路径是否正确。'
        } else if (err.message.includes('500')) {
          errorMessage.message = `❌ 服务器内部错误，可能是模型 ${selectedModel.value.name} 暂时不可用。请尝试切换其他模型。`
        } else {
          errorMessage.message = `❌ 请求失败：${err.message}\n\n当前使用模型：${selectedModel.value.name} (${selectedModel.value.platform})\n请检查网络连接或尝试切换其他模型。`
        }
      }

      scrollToBottom()
    })
}

// 图片生成功能
const generateImage = async (prompt: string) => {
  isGeneratingImage.value = true
  
  // 添加用户消息
  chatMessages.value.push({
    id: generateUUID(),
    message: prompt,
    role: 'user',
    type: 'image',
    imagePrompt: prompt
  })

  // 添加加载中的助手消息
  let resId = generateUUID()
  chatMessages.value.push({
    id: resId,
    message: '正在生成图片，请稍候...',
    role: 'assistant',
    type: 'image'
  })

  scrollToBottom()

  // 清空输入框
  message.value = ''
  if (messageInputRef.value) {
    messageInputRef.value.style.height = 'auto'
  }

  const requestBody = {
    platform: selectedModel.value.platform,
    model: selectedModel.value.id,
    prompt: prompt,
    size: '1024x1024' // 默认尺寸，可以根据需要调整
  }

  console.log('🎨 发送图片生成请求:', {
    url: '/api/ai/create/image',
    model: selectedModel.value.name,
    platform: selectedModel.value.platform,
    prompt: prompt.substring(0, 50) + '...'
  })

  try {
    const response = await fetch('/api/ai/create/image', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
      },
      body: JSON.stringify(requestBody)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const imageResult = await response.json()
    
    console.log('📦 图片生成API返回:', imageResult)
    
    // 更新助手消息显示生成的图片
    const imageMessage = chatMessages.value.find(item => item.id === resId)
    const imageUrl = imageResult.image || imageResult.url // 兼容不同的返回字段名
    
    if (imageMessage && imageUrl) {
      imageMessage.message = '图片生成完成'
      imageMessage.imageUrl = imageUrl
      imageMessage.imagePrompt = prompt
      console.log('✅ 图片生成成功:', imageUrl)
    } else {
      console.error('❌ 图片URL获取失败:', {
        hasImageMessage: !!imageMessage,
        imageUrl: imageUrl,
        fullResponse: imageResult
      })
      
      if (imageMessage) {
        imageMessage.message = '❌ 图片生成失败：无法获取图片URL'
      }
    }

  } catch (error: any) {
    console.error('❌ 图片生成失败:', error)
    
    // 更新错误消息
    const errorMessage = chatMessages.value.find(item => item.id === resId)
    if (errorMessage) {
      if (error?.message?.includes('403')) {
        errorMessage.message = '❌ 访问被拒绝，请先登录后再尝试生成图片。'
      } else if (error?.message?.includes('401')) {
        errorMessage.message = '❌ 未授权访问，请重新登录后再试。'
      } else if (error?.message?.includes('500')) {
        errorMessage.message = `❌ 服务器内部错误，模型 ${selectedModel.value.name} 可能暂时不支持图片生成。`
      } else {
        errorMessage.message = `❌ 图片生成失败：${error?.message || '未知错误'}\n\n当前模型：${selectedModel.value.name} (${selectedModel.value.platform})`
      }
    }
  } finally {
    isGeneratingImage.value = false
    scrollToBottom()
  }
}

// 初始化
onMounted(() => {
  // 恢复侧边栏状态
  const savedSidebarState = localStorage.getItem('sidebarVisible')
  if (savedSidebarState !== null) {
    showSidebar.value = savedSidebarState === 'true'
  }

  // 初始化默认模型
  const defaultModel = defaultModelForMode.value
  if (defaultModel) {
    selectedModel.value = defaultModel
    currentModel.value = defaultModel.name
    console.log('🚀 初始化默认模型:', defaultModel.name)
  }

  // 聚焦输入框
  if (messageInputRef.value) {
    messageInputRef.value.focus()
  }

  // 检查是否有token
  if (!isLoggedIn.value) {
    console.warn('未检测到登录token，可能需要先登录才能访问API')
    // 可以在这里添加一个提示，告诉用户需要登录
    chatMessages.value.push({
      id: generateUUID(),
      message: '提示：您可能需要先登录才能使用聊天功能。如果遇到API访问问题，请点击右上角的"登录"按钮进行登录。',
      role: 'assistant',
    })
  } else {
    console.log('✅ 用户已登录，token有效')
  }

  // 添加键盘快捷键
  document.addEventListener('keydown', (e) => {
    // Cmd/Ctrl+Enter 发送消息
    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
      sendMessageClick()
    }
  })

  // 添加点击外部关闭模型选择器的事件监听
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>
<template>
  <div class="glass-background font-sans h-screen flex text-glass-text">
    <!-- 侧边栏 -->
    <Sidebar 
      v-if="showSidebar"
      @chat-selected="handleChatSelected"
      @view-all-history="handleViewAllHistory"
      @upgrade-to-pro="handleUpgradeToPro"
      @open-settings="handleOpenSettings"
      @collapse-changed="handleSidebarCollapseChange"
      class="flex-shrink-0" />
    
    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col relative">
      <!-- 侧边栏切换按钮 -->
      <button 
        @click="toggleSidebar"
        class="absolute top-4 z-50 glass-button p-3 rounded-lg transition-all duration-200 hover:scale-105"
        :class="{ 
          'left-4': !showSidebar,
          'left-[25rem]': showSidebar && !sidebarCollapsed,
          'left-20': showSidebar && sidebarCollapsed
        }"
        :title="showSidebar ? '隐藏侧边栏' : '显示侧边栏'">
        <i :class="showSidebar ? 'fas fa-sidebar fa-flip-horizontal' : 'fas fa-bars'" class="text-glass-text"></i>
      </button>
      <!-- 顶部导航栏 -->
      <header class="glass-effect px-6 py-4 flex items-center justify-between relative z-[9000]">
        <div class="flex items-center space-x-4">
          <div class="w-8"></div> <!-- 占位符，为侧边栏按钮留空间 -->
        <h1 class="text-2xl font-semibold text-glass-text">AI Chat</h1>
        
        <!-- 模型选择器 -->
        <div class="relative model-selector-container z-[9998]">
          <button @click="toggleModelSelector" 
            class="text-base text-glass-text-muted model-selector-button px-4 py-2 rounded-full hover:bg-glass-bg-hover transition-all cursor-pointer flex items-center space-x-2">
            <span>{{ currentModel }}</span>
            <i class="fas fa-chevron-down text-xs transition-transform" :class="{ 'rotate-180': showModelSelector }"></i>
          </button>
          
          <!-- 下拉选择菜单 -->
          <div v-if="showModelSelector" 
            ref="modelDropdownRef"
            class="absolute top-full left-0 mt-2 model-dropdown glass-card rounded-xl shadow-xl border border-glass-border min-w-80 z-[9999] overflow-hidden max-h-96 overflow-y-auto backdrop-blur-xl">
            <div class="p-2">
              <div class="text-xs text-glass-text-muted px-3 py-2 font-medium">选择 AI 模型</div>
              
              <!-- 当前模式提示 -->
              <div class="px-3 py-2 mb-3">
                <div class="flex items-center space-x-2 text-xs text-glass-text-muted">
                  <i :class="chatMode === 'text' ? 'fas fa-comment-dots' : 'fas fa-image'"></i>
                  <span>{{ chatMode === 'text' ? '文本聊天模型' : '图片生成模型' }}</span>
                </div>
              </div>

              <!-- OpenAI 模型组 -->
              <div v-if="filteredModels.filter(m => m.platform === 'openai').length > 0" class="mb-4">
                <div class="glass-section-header text-xs text-glass-text-muted px-3 py-2 font-semibold bg-glass-bg rounded-lg mb-2">
                  <i class="fas fa-brain mr-2"></i>OpenAI
                </div>
                <div v-for="model in filteredModels.filter(m => m.platform === 'openai')" :key="model.id" 
                  @click="selectModel(model)"
                  class="model-option glass-effect p-3 mx-1 mb-2 rounded-xl cursor-pointer hover:bg-glass-bg-hover transition-all duration-200 transform hover:scale-[1.02]"
                  :class="{ 'model-selected bg-glass-bg-hover border-glass-primary': selectedModel.id === model.id }">
                  <div class="flex-1">
                    <div class="flex items-center justify-between">
                      <span class="font-semibold text-glass-text">{{ model.name }}</span>
                      <span v-if="selectedModel.id === model.id" class="text-glass-primary">
                        <i class="fas fa-check-circle"></i>
                      </span>
                    </div>
                    <div class="text-xs text-glass-text-muted mt-1">{{ model.description }}</div>
                  </div>
                </div>
              </div>
              
              <!-- 阿里云模型组 -->
              <div v-if="filteredModels.filter(m => m.platform === 'ali').length > 0" class="mb-2">
                <div class="glass-section-header text-xs text-glass-text-muted px-3 py-2 font-semibold bg-glass-bg rounded-lg mb-2">
                  <i class="fas fa-cloud mr-2"></i>阿里云
                </div>
                <div v-for="model in filteredModels.filter(m => m.platform === 'ali')" :key="model.id" 
                  @click="selectModel(model)"
                  class="model-option glass-effect p-3 mx-1 mb-2 rounded-xl cursor-pointer hover:bg-glass-bg-hover transition-all duration-200 transform hover:scale-[1.02]"
                  :class="{ 'model-selected bg-glass-bg-hover border-glass-primary': selectedModel.id === model.id }">
                  <div class="flex-1">
                    <div class="flex items-center justify-between">
                      <span class="font-semibold text-glass-text">{{ model.name }}</span>
                      <span v-if="selectedModel.id === model.id" class="text-glass-primary">
                        <i class="fas fa-check-circle"></i>
                      </span>
                    </div>
                    <div class="text-xs text-glass-text-muted mt-1">{{ model.description }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="flex items-center space-x-3">
        <!-- 登录按钮 - 仅在未登录时显示 -->
        <a v-if="!isLoggedIn" href="/login"
          class="glass-button px-3 py-1 text-glass-text rounded-md transition-colors">
          登录
        </a>

        <button class="glass-button p-2 rounded-lg transition-colors" title="分享对话">
          <i class="fas fa-share-alt text-glass-text"></i>
        </button>
        <button class="glass-button p-2 rounded-lg transition-colors" title="更多选项">
          <i class="fas fa-ellipsis-v text-glass-text"></i>
        </button>
        </div>
      </header>

        <!-- 主聊天区域 -->
        <main class="flex-1 overflow-hidden flex flex-col">
      <!-- 对话内容区域 -->
      <div class="flex-1 overflow-y-auto px-6 py-4" id="chatContainer" ref="chatContainerRef">
        <!-- 欢迎消息 -->
        <div v-if="chatMessages.length === 0" class="max-w-4xl mx-auto">
          <div class="text-center py-12 mb-8">
            <div class="w-16 h-16 glass-card rounded-full flex items-center justify-center mx-auto mb-4">
              <i class="fas fa-robot text-glass-primary text-2xl"></i>
            </div>
            <h2 class="text-3xl font-bold text-glass-text mb-2">你好！我是AI助手</h2>
            <p class="text-lg text-glass-text-muted mb-6">我可以帮助您解答问题、提供建议、协助创作等。请随时开始对话！</p>

            <!-- 快速开始建议 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl mx-auto">
              <button @click="setSuggestedMessage('帮我想一些创新的项目想法')"
                class="glass-card p-4 rounded-lg hover:bg-glass-bg-hover transition-all text-left group">
                <div class="flex items-center space-x-3 mb-2">
                  <i class="fas fa-lightbulb text-glass-text"></i>
                  <h3 class="font-medium text-lg text-glass-text">创意灵感</h3>
                </div>
                <p class="text-base text-glass-text-muted">帮我想一些创新的项目想法</p>
              </button>

              <button @click="setSuggestedMessage('解释代码或帮助调试问题')"
                class="glass-card p-4 rounded-lg hover:bg-glass-bg-hover transition-all text-left group">
                <div class="flex items-center space-x-3 mb-2">
                  <i class="fas fa-code text-glass-text"></i>
                  <h3 class="font-medium text-lg text-glass-text">编程助手</h3>
                </div>
                <p class="text-base text-glass-text-muted">解释代码或帮助调试问题</p>
              </button>

              <button @click="setSuggestedMessage('协助撰写文章、邮件或文案')"
                class="glass-card p-4 rounded-lg hover:bg-glass-bg-hover transition-all text-left group">
                <div class="flex items-center space-x-3 mb-2">
                  <i class="fas fa-pen-fancy text-glass-text"></i>
                  <h3 class="font-medium text-lg text-glass-text">写作助手</h3>
                </div>
                <p class="text-base text-glass-text-muted">协助撰写文章、邮件或文案</p>
              </button>

              <button @click="setSuggestedMessage('解答学术问题或制定学习计划')"
                class="glass-card p-4 rounded-lg hover:bg-glass-bg-hover transition-all text-left group">
                <div class="flex items-center space-x-3 mb-2">
                  <i class="fas fa-graduation-cap text-glass-text"></i>
                  <h3 class="font-medium text-lg text-glass-text">学习指导</h3>
                </div>
                <p class="text-base text-glass-text-muted">解答学术问题或制定学习计划</p>
              </button>
            </div>
          </div>
        </div>

        <!-- 聊天消息列表 -->
        <div class="max-w-4xl mx-auto space-y-6" id="messagesContainer">
          <div v-for="(chatMessage, index) in chatMessages" :key="chatMessage.id" :class="{ 'animate-fade-in': true }"
            :style="{ animationDelay: `${index * 0.1}s` }">

            <!-- 用户消息 -->
            <div v-if="chatMessage.role === 'user'" class="flex justify-end">
              <div class="max-w-3xl">
                <div class="glass-card text-glass-text rounded-2xl rounded-br-md px-4 py-3">
                  <div class="flex items-center space-x-2 mb-2" v-if="chatMessage.type === 'image'">
                    <i class="fas fa-image text-glass-primary"></i>
                    <span class="text-sm text-glass-text-muted">图片生成请求</span>
                  </div>
                  <p class="whitespace-pre-wrap text-base">{{ chatMessage.message }}</p>
                </div>
                <div class="flex items-center justify-end mt-2 space-x-2 text-sm text-glass-text-muted">
                  <span>{{ formatTime(new Date()) }}</span>
                  <i class="fas fa-check text-glass-primary"></i>
                </div>
              </div>
            </div>

            <!-- AI回复 -->
            <div v-else class="flex items-start space-x-3">
              <div class="w-8 h-8 glass-card rounded-full flex items-center justify-center flex-shrink-0">
                <i class="fas fa-robot text-glass-primary text-sm"></i>
              </div>
              <div class="flex-1 max-w-3xl">
                <div class="glass-effect rounded-2xl rounded-tl-md px-4 py-3">
                  <!-- 加载状态 -->
                  <div v-if="chatMessage.message === '' || (chatMessage.type === 'image' && chatMessage.message.includes('正在生成'))" class="flex space-x-2 py-2">
                    <div class="w-2 h-2 bg-glass-text-muted rounded-full animate-bounce"></div>
                    <div class="w-2 h-2 bg-glass-text-muted rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                    <div class="w-2 h-2 bg-glass-text-muted rounded-full animate-bounce" style="animation-delay: 0.4s"></div>
                    <span v-if="chatMessage.type === 'image'" class="ml-2 text-sm text-glass-text-muted">{{ chatMessage.message }}</span>
                  </div>
                  
                  <!-- 图片内容 -->
                  <div v-else-if="chatMessage.type === 'image' && chatMessage.imageUrl" class="space-y-3">
                    <div class="text-glass-text">{{ chatMessage.message }}</div>
                    <div class="image-container">
                      <img :src="chatMessage.imageUrl" :alt="chatMessage.imagePrompt" 
                        class="generated-image rounded-lg max-w-full h-auto cursor-pointer"
                        @click="() => openImage(chatMessage.imageUrl!)"
                        @error="(event) => handleImageError(event, chatMessage.id)"
                        @load="() => console.log('✅ 图片加载成功:', chatMessage.imageUrl)">
                    </div>
                    <div class="text-xs text-glass-text-muted">
                      <i class="fas fa-palette mr-1"></i>
                      提示词：{{ chatMessage.imagePrompt }}
                    </div>
                  </div>
                  
                  <!-- 文本内容 -->
                  <div v-else class="prose prose-base max-w-none whitespace-pre-wrap text-glass-text">
                    <div v-html="formatMessageContent(chatMessage.message)"></div>
                  </div>
                </div>
                <div class="flex items-center mt-2 space-x-3 text-sm text-glass-text-muted">
                  <span>{{ formatTime(new Date()) }}</span>
                  <button class="hover:text-glass-text transition-colors" title="复制"
                    @click="copyMessage(chatMessage.message)">
                    <i class="fas fa-copy"></i>
                  </button>
                  <button class="hover:text-glass-text transition-colors" title="重新生成" @click="regenerateMessage(index)">
                    <i class="fas fa-redo"></i>
                  </button>
                  <button class="hover:text-glass-text transition-colors" title="点赞">
                    <i class="far fa-thumbs-up"></i>
                  </button>
                  <button class="hover:text-glass-text transition-colors" title="点踩">
                    <i class="far fa-thumbs-down"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

        <!-- 输入区域 -->
        <div class="glass-effect border-t px-6 py-4">
        <div class="max-w-4xl mx-auto">
          <!-- 模式切换按钮 -->
          <div class="flex justify-center mb-4">
            <div class="glass-card rounded-full p-1 flex items-center">
              <button @click="toggleChatMode"
                class="mode-switch-button px-4 py-2 rounded-full transition-all duration-200 flex items-center space-x-2"
                :class="{ 'active': chatMode === 'text' }">
                <i class="fas fa-comment-dots"></i>
                <span>文本聊天</span>
              </button>
              <button @click="toggleChatMode"
                class="mode-switch-button px-4 py-2 rounded-full transition-all duration-200 flex items-center space-x-2"
                :class="{ 'active': chatMode === 'image' }">
                <i class="fas fa-image"></i>
                <span>图片生成</span>
              </button>
            </div>
          </div>

          <div class="relative">
            <div class="flex items-end space-x-4">
              <!-- 附件按钮 -->
              <button class="glass-button p-3 rounded-lg transition-colors flex-shrink-0" title="上传文件">
                <i class="fas fa-paperclip text-glass-text"></i>
              </button>

              <!-- 输入框 -->
              <div class="flex-1">
                <textarea v-model="message" ref="messageInputRef" 
                  :placeholder="chatMode === 'text' ? '输入您的问题或想法...' : '描述您想要生成的图片...'"
                  class="glass-input w-full resize-none rounded-xl px-4 py-3 outline-none transition-all duration-200 max-h-32 text-base text-glass-text placeholder:text-glass-text-muted"
                  rows="1" @input="adjustTextareaHeight" @keydown.enter.exact.prevent="sendMessageClick"
                  @keydown.enter.shift="handleShiftEnter"></textarea>
              </div>

              <!-- 发送按钮 -->
              <button @click="sendMessageClick"
                class="glass-button p-3 rounded-lg transition-colors flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
                :disabled="!message.trim() || isLoading || isGeneratingImage"
                :title="chatMode === 'text' ? '发送消息' : '生成图片'">
                <i :class="chatMode === 'text' ? 'fas fa-paper-plane' : 'fas fa-magic'" class="text-glass-text"></i>
              </button>

              <!-- 语音按钮 -->
              <button class="glass-button p-3 rounded-lg transition-colors flex-shrink-0" title="语音输入">
                <i class="fas fa-microphone text-glass-text"></i>
              </button>
            </div>

            <!-- 输入提示 -->
            <div class="flex items-center justify-between mt-2 text-sm text-glass-text-muted">
              <span>按 Shift + Enter 换行，Enter 发送</span>
              <span id="charCount">{{ message.length }} / 2000</span>
            </div>
          </div>
        </div>
        </div>
        </main>
      </div>
    </div>
  
</template>

<style scoped>
/* 自定义样式 */
.font-sans {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
}

/* 毛玻璃效果样式 */
.glass-background {
  background: linear-gradient(135deg, #f0f2f5 0%, #ffffff 50%, #f8f9fa 100%);
  min-height: 100vh;
}

.glass-effect {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-button {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.glass-button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.glass-input {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.glass-input:focus {
  background: rgba(255, 255, 255, 0.95);
  border-color: rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 颜色变量 */
:root {
  --glass-light: #ffffff;
  --glass-light-secondary: #f8f9fa;
  --glass-dark: #1a1a1a;
  --glass-border: rgba(0, 0, 0, 0.08);
  --glass-primary: #000000;
  --glass-primary-hover: rgba(0, 0, 0, 0.8);
  --glass-secondary: #ffffff;
  --glass-text: #1f2937;
  --glass-text-muted: rgba(31, 41, 55, 0.7);
  --glass-bg: rgba(255, 255, 255, 0.7);
  --glass-bg-hover: rgba(255, 255, 255, 0.9);
  --glass-shadow: rgba(0, 0, 0, 0.1);
}

/* Tailwind自定义颜色类 */
.text-glass-primary { color: var(--glass-primary); }
.text-glass-text { color: var(--glass-text); }
.text-glass-text-muted { color: var(--glass-text-muted); }
.bg-glass-bg { background-color: var(--glass-bg); }
.bg-glass-bg-hover { background-color: var(--glass-bg-hover); }
.border-glass-border { border-color: var(--glass-border); }
.border-glass-primary { border-color: var(--glass-primary); }
.focus\:ring-glass-primary:focus { --tw-ring-color: var(--glass-primary); }
.hover\:text-glass-primary:hover { color: var(--glass-primary); }
.hover\:bg-glass-bg-hover:hover { background-color: var(--glass-bg-hover); }
.placeholder\:text-glass-text-muted::placeholder { color: var(--glass-text-muted); }

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

/* 输入框聚焦效果 */
textarea:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(16, 163, 127, 0.2);
}

/* 消息内容格式化 */
.prose {
  line-height: 1.6;
}

.prose h4 {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
  font-size: 1.1rem;
}

.prose p {
  margin-bottom: 0.75rem;
}

.prose ul,
.prose ol {
  margin-left: 1.5rem;
  margin-bottom: 0.75rem;
}

.prose code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.125rem 0.25rem;
  border-radius: 0.25rem;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 0.9em;
}

.prose pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.75rem;
  border-radius: 0.375rem;
  overflow-x: auto;
  margin-bottom: 1rem;
}

.prose pre code {
  background-color: transparent;
  padding: 0;
}

/* 建议卡片悬停效果 */
.suggestion-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* 加载动画 */
@keyframes bounce {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-4px);
  }
}

.animate-bounce {
  animation: bounce 1.5s infinite;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

/* 模型选择器按钮样式 */
.model-selector-button {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.6) 100%);
  backdrop-filter: blur(15px) saturate(1.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 2px 8px rgba(0, 0, 0, 0.08),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
}

.model-selector-button:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
  transform: translateY(-1px);
  box-shadow: 
    0 4px 12px rgba(0, 0, 0, 0.12),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
}

.model-selector-container .fa-chevron-down {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.rotate-180 {
  transform: rotate(180deg);
}

/* 模型下拉菜单毛玻璃效果 */
.model-dropdown {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.85) 100%);
  backdrop-filter: blur(25px) saturate(1.8);
  -webkit-backdrop-filter: blur(25px) saturate(1.8);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.15),
    0 4px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.2);
  /* 确保始终在最上层 */
  z-index: 9999 !important;
  position: absolute !important;
  /* 添加更强的边框来突出层级 */
  border: 2px solid rgba(255, 255, 255, 0.3);
}

/* 分组标题样式 */
.glass-section-header {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0.5) 100%);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* 模型选项样式 */
.model-option {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.4) 100%);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.model-option:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.6) 100%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: rgba(255, 255, 255, 0.4);
}

.model-selected {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%) !important;
  border: 2px solid rgba(0, 0, 0, 0.1) !important;
  box-shadow: 
    0 4px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.8) !important;
}

/* 下拉菜单动画 */
.model-dropdown-enter-active,
.model-dropdown-leave-active {
  transition: all 0.3s ease;
}

.model-dropdown-enter-from,
.model-dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

/* 模型选项动画 */
.model-option {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.model-option:active {
  transform: scale(0.98);
}

/* 响应式调整 */
@media (max-width: 640px) {
  .px-6 {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .max-w-4xl {
    max-width: 100%;
  }

  .grid-cols-1 {
    grid-template-columns: 1fr;
  }

  /* 移动端模型选择器调整 */
  .model-selector-container .min-w-80 {
    min-width: 300px;
    right: 0;
    left: auto;
    max-width: calc(100vw - 2rem);
  }
}

/* 模式切换按钮样式 */
.mode-switch-button {
  background: transparent;
  color: var(--glass-text-muted);
  border: none;
  cursor: pointer;
}

.mode-switch-button.active {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
  color: var(--glass-text);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mode-switch-button:hover:not(.active) {
  background: rgba(255, 255, 255, 0.3);
  color: var(--glass-text);
}

/* 生成图片样式 */
.generated-image {
  max-width: 400px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.generated-image:hover {
  transform: scale(1.02);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.image-container {
  position: relative;
  display: inline-block;
}

.image-container::after {
  content: '🔍 点击查看大图';
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.2s ease;
  pointer-events: none;
}

.image-container:hover::after {
  opacity: 1;
}

/* 层级管理 - 确保模型选择器始终在最上层 */
.model-selector-container {
  position: relative;
  z-index: 9998;
}

.model-dropdown {
  position: absolute !important;
  z-index: 9999 !important;
  /* 添加更强的模糊效果来突出层级感 */
  backdrop-filter: blur(30px) saturate(2) !important;
  -webkit-backdrop-filter: blur(30px) saturate(2) !important;
}
</style>
